<template>
  <div class="w-screen h-screen overflow-hidden relative mt-[-80px]">
    <!-- Background Image -->
    <v-img
      src="https://restatic.vjshi.com/vjshi-frontend-remix-video/build/_assets/banner-D62SQXSA.png"
      cover
      height="100vh"
      width="100vw"
    >
      <!-- Header -->
      <v-app-bar
        color="transparent"
        height="80"
        flat
        class="px-11"
      >
        <div class="d-flex align-center">
          <v-img
            width="100"
            height="40"
            src="../assets/logo.jpg"
            class="cursor-pointer"
            @click="router.push('/')"
          />
          <v-divider
            vertical
            class="mx-4 bg-white"
            thickness="2"
          />
          <span class="text-h6 font-weight-medium text-white">让创意更有价值</span>
        </div>
      </v-app-bar>

      <!-- Login/Register Card -->
      <v-card
        width="500"
        class="position-absolute"
        style="right: 80px; top: 50%; transform: translateY(-50%)"
        elevation="4"
      >
        <v-window v-model="formType">
          <!-- Login Form -->
          <v-window-item value="login">
            <v-card-text>
              <div class="text-center pt-8 pb-4">
                <h3 class="text-h5 font-weight-medium">欢迎回来</h3>
              </div>

              <div class="px-8">
                <v-tabs
                  v-model="loginType"
                  color="black"
                  grow
                >
                  <v-tab value="phone">
                    <v-icon start>mdi-phone</v-icon>
                    手机号登录
                  </v-tab>
                  <v-tab value="password">
                    <v-icon start>mdi-lock</v-icon>
                    密码登录
                  </v-tab>
                </v-tabs>

                <v-form ref="loginFormRef" class="pt-6">
                  <v-text-field
                    v-model="loginForm.phone"
                    label="手机号"
                    :rules="[rules.required, rules.phone]"
                    variant="outlined"
                    class="mb-4"
                    bg-color="white"
                  />

                  <div v-if="loginType === 'phone'" class="d-flex gap-4 mb-4">
                    <v-text-field
                      v-model="loginForm.sms_code"
                      label="验证码"
                      :rules="[rules.required, rules.smsCode]"
                      variant="outlined"
                      bg-color="white"
                    />
                    <v-btn
                      variant="outlined"
                      color="black"
                      height="56"
                      :loading="loading.loginSms"
                      :disabled="!isValidPhone(loginForm.phone) || loginSmsTimer > 0"
                      @click="handleGetSmsCode(false)"
                    >
                      {{ loginSmsTimer > 0 ? `${loginSmsTimer}s` : '获取验证码' }}
                    </v-btn>
                  </div>

                  <v-text-field
                    v-else
                    v-model="loginForm.password"
                    :type="showLoginPassword ? 'text' : 'password'"
                    :append-inner-icon="showLoginPassword ? 'mdi-eye' : 'mdi-eye-off'"
                    label="密码"
                    :rules="[rules.required, rules.password]"
                    variant="outlined"
                    class="mb-4"
                    bg-color="white"
                    @click:append-inner="showLoginPassword = !showLoginPassword"
                  />

                  <div class="d-flex flex-column align-center mt-8">
                    <v-btn
                      color="black"
                      size="x-large"
                      rounded="pill"
                      min-width="200"
                      :loading="loading.login"
                      @click="handleLogin"
                    >
                      登录
                    </v-btn>
                    <div class="mt-4 text-body-2 text-grey-darken-1">
                      还没有账号？
                      <a
                        class="text-black text-decoration-none cursor-pointer"
                        @click="formType = 'register'"
                      >
                        立即注册
                      </a>
                    </div>
                  </div>
                </v-form>
              </div>
            </v-card-text>
          </v-window-item>

          <!-- Register Form -->
          <v-window-item value="register">
            <v-card-text>
              <div class="text-center pt-8 pb-4 position-relative">
                <v-btn
                  icon="mdi-arrow-left"
                  variant="text"
                  color="black"
                  class="position-absolute"
                  style="left: 16px; top: 32px"
                  @click="formType = 'login'"
                />
                <h3 class="text-h5 font-weight-medium">注册账号</h3>
              </div>

              <div class="px-8">
                <v-form ref="registerFormRef">
                  <v-text-field
                    v-model="registerForm.phone"
                    label="手机号"
                    :rules="[rules.required, rules.phone]"
                    variant="outlined"
                    class="mb-4"
                    bg-color="white"
                  />

                  <div class="d-flex gap-4 mb-4">
                    <v-text-field
                      v-model="registerForm.sms_code"
                      label="验证码"
                      :rules="[rules.required, rules.smsCode]"
                      variant="outlined"
                      bg-color="white"
                    />
                    <v-btn
                      variant="outlined"
                      color="black"
                      height="56"
                      :loading="loading.registerSms"
                      :disabled="!isValidPhone(registerForm.phone) || registerSmsTimer > 0"
                      @click="handleGetSmsCode(true)"
                    >
                      {{ registerSmsTimer > 0 ? `${registerSmsTimer}s` : '获取验证码' }}
                    </v-btn>
                  </div>

                  <v-text-field
                    v-model="registerForm.password"
                    :type="showRegisterPassword ? 'text' : 'password'"
                    :append-inner-icon="showRegisterPassword ? 'mdi-eye' : 'mdi-eye-off'"
                    label="设置密码"
                    :rules="[rules.required, rules.password]"
                    variant="outlined"
                    class="mb-4"
                    bg-color="white"
                    @click:append-inner="showRegisterPassword = !showRegisterPassword"
                  />

                  <v-text-field
                    v-model="registerForm.confirmPassword"
                    :type="showConfirmPassword ? 'text' : 'password'"
                    :append-inner-icon="showConfirmPassword ? 'mdi-eye' : 'mdi-eye-off'"
                    label="确认密码"
                    :rules="[rules.required, rules.password, confirmPasswordRule]"
                    variant="outlined"
                    class="mb-4"
                    bg-color="white"
                    @click:append-inner="showConfirmPassword = !showConfirmPassword"
                  />

                  <div class="d-flex justify-center mt-8">
                    <v-btn
                      color="black"
                      size="x-large"
                      rounded="pill"
                      min-width="200"
                      :loading="loading.register"
                      @click="handleRegister"
                    >
                      注册
                    </v-btn>
                  </div>
                </v-form>
              </div>
            </v-card-text>
          </v-window-item>
        </v-window>
      </v-card>
    </v-img>

    <!-- Snackbar -->
    <v-snackbar
      v-model="snackbar.show"
      :color="snackbar.color"
      :timeout="3000"
      location="top"
    >
      {{ snackbar.text }}
    </v-snackbar>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { smsCode } from '@/api/login'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// Form refs for validation
const loginFormRef = ref(null)
const registerFormRef = ref(null)

// Form type control (login/register)
const formType = ref('login')
const loginType = ref('phone')

// Password visibility controls
const showLoginPassword = ref(false)
const showRegisterPassword = ref(false)
const showConfirmPassword = ref(false)

// Form data
const loginForm = ref({
  phone: '',
  sms_code: '',
  password: ''
})

const registerForm = ref({
  phone: '',
  sms_code: '',
  password: '',
  confirmPassword: ''
})

// Loading states
const loading = ref({
  login: false,
  register: false,
  loginSms: false,
  registerSms: false
})

// SMS timers
const loginSmsTimer = ref(0)
const registerSmsTimer = ref(0)

// Snackbar state
const snackbar = ref({
  show: false,
  text: '',
  color: 'error'
})

// Validation rules
const rules = {
  required: v => !!v || '此项为必填项',
  phone: v => /^1[3-9]\d{9}$/.test(v) || '请输入正确的手机号',
  smsCode: v => /^\d{6}$/.test(v) || '验证码为6位数字',
  password: v => v?.length >= 6 || '密码至少6位'
}

const confirmPasswordRule = v => v === registerForm.value.password || '两次输入的密码不一致'

// Methods
const isValidPhone = (phone) => {
  return /^1[3-9]\d{9}$/.test(phone)
}

const showMessage = (message, color = 'error') => {
  snackbar.value = {
    show: true,
    text: message,
    color
  }
}

const startTimer = (isRegister) => {
  const timerRef = isRegister ? registerSmsTimer : loginSmsTimer
  timerRef.value = 60
  const timer = setInterval(() => {
    timerRef.value--
    if (timerRef.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const handleGetSmsCode = async (isRegister) => {
  const phone = isRegister ? registerForm.value.phone : loginForm.value.phone
  if (!isValidPhone(phone)) return

  try {
    loading.value[isRegister ? 'registerSms' : 'loginSms'] = true
    await smsCode(phone)
    startTimer(isRegister)
    showMessage('验证码已发送', 'success')
  } catch (error) {
    showMessage(error.response?.data?.message || '验证码发送失败')
  } finally {
    loading.value[isRegister ? 'registerSms' : 'loginSms'] = false
  }
}

const handleLogin = async () => {
  const { valid } = await loginFormRef.value?.validate() || {}
  if (!valid) return

  try {
    loading.value.login = true
    const loginData = {
      phone: loginForm.value.phone,
      type: loginType.value === 'phone' ? 'sms' : 'password',
      ...(loginType.value === 'phone'
        ? { sms_code: loginForm.value.sms_code }
        : { password: loginForm.value.password }
      )
    }

    if (loginType.value === 'phone') {
      await authStore.login(loginData)
    } else {
      await authStore.loginByPassword({
        username: loginForm.value.phone,
        password: loginForm.value.password
      })
    }

    if (route.query.redirect) {
      router.push(route.query.redirect)
    } else {
      router.push('/')
    }
  } catch (error) {
    showMessage(error.response?.data?.message || '登录失败')
  } finally {
    loading.value.login = false
  }
}

const handleRegister = async () => {
  const { valid } = await registerFormRef.value?.validate() || {}
  if (!valid) return

  try {
    loading.value.register = true
    await authStore.register({
      phone: registerForm.value.phone,
      sms_code: registerForm.value.sms_code,
      password: registerForm.value.password
    })

    showMessage('注册成功', 'success')
    loginForm.value.phone = registerForm.value.phone
    formType.value = 'login'
  } catch (error) {
    showMessage(error.response?.data?.message || '注册失败')
  } finally {
    loading.value.register = false
  }
}
</script>

<style scoped>
*::-webkit-scrollbar {
  display: none;
}
* {
  scrollbar-width: none;
  -ms-overflow-style: none;
}
</style>
